#include <iostream>
#include <pthread.h>
#include "Sock.hpp"

static const uint16_t defaultport = 8888;

class HttpServer;
class ThreadData
{
public:
    ThreadData(int sock, const std::string& ip, const uint16_t& port, HttpServer* hsvrp)
        :_sock(sock), _ip(ip), _port(port), _hsvrp(hsvrp)
    {}
    ~ThreadData()
    {}
private:
    int _sock;
    std::string _ip;
    uint16_t _port;
    HttpServer* _hsvrp;
};



class HttpServer
{
public:
    HttpServer(uint16_t port)
        : port_(defaultport)
    {
    }

    void InitServer()
    {
        listensock_.Socket();
        listensock_.Bind(port_);
        listensock_.Listen();
    }

    static void* threadRoutine(void* args)
    {
        pthread_detach(pthread_self());
        ThreadData* td = static_cast<ThreadData*>(args);

        delete td;
    }

    void Start()
    {
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sock = listensock_.Accept(&clientip, &clientport);
            if (sock < 0)
            {
                continue;
            }
            pthread_t tid;
            ThreadData* td = new ThreadData(sock, clientip, clientport, this);
            pthread_create(&tid, nullptr, threadRoutine, td);
        }
    }
    ~HttpServer()
    {
    }

private:
    uint16_t port_;
    Sock listensock_;
};